/*
 * SessionBean.java
 *
 * Created on 15 juil. 2008, 11:39:39
 */
package centralehotelagenceweb;

import centralehotel.metier.client.AgenceMetierLocal;
import centralehotel.metier.client.ReservationMetierLocal;
import centralehotel.modele.Agence;
import centralehotel.modele.Client;
import centralehotel.modele.FicheHotel;
import centralehotel.modele.GestionnaireHotel;
import centralehotel.modele.Pays;
import centralehotel.modele.PeriodeTarif;
import centralehotel.modele.Reservation;
import centralehotel.modele.TypeChambre;
import centralehotel.modele.Ville;
import centralehotelagencebean.AbstractBean;
import com.sun.faces.config.beans.ApplicationBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class SessionBean extends AbstractBean {
    @EJB
    private ReservationMetierLocal reservationMetier;

    @EJB
    private AgenceMetierLocal agenceMetier;
    private GestionnaireHotel test;
    private List<Pays> allPays;
    private List<SelectItem> listeVille;
    private Ville selectedVille;
    private List<SelectItem> listeHotel;
    private FicheHotel selectedHotel;
    private ListDataModel listePeriode;
    private PeriodeTarif currentPeriode;
    private  Client client;
    private Reservation reservation;
    private List<SelectItem> listeTypeChambre;
    private TypeChambre selectedTypeChambre;
    private Agence currentAgence;
    private float  total =0;
    private boolean confirmTotal = false;
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>
    /**
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionBean() {
    }

    protected ApplicationBean getApplicationBean() {
        return (ApplicationBean) getBean("ApplicationBean");
    }
    
    private AgenceMetierLocal lookupAgenceMetier() {
        try {
            Context c = new InitialContext();
            return (AgenceMetierLocal) c.lookup("java:comp/env/AgenceMetier");
        } catch (NamingException ne) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
// ************************* ACCESSEURS *******************************
    public void setAllPays(List<Pays> allPays) {
        this.allPays = allPays;
    }

    public List<SelectItem> getListeVille() {
        System.out.println("methode GEtListeVille");
        if (listeVille == null) {
            return buildSelectCollection(agenceMetier.getAllVille(), "nom");
        } else {
            return listeVille;
        }
    }

    public void setListeVille(List<SelectItem> listeVille) {
        this.listeVille = listeVille;
    }

    public Ville getSelectedVille() {
        return selectedVille;
    }

    public void setSelectedVille(Ville selectedVille) {
        this.selectedVille = selectedVille;
        System.out.println("MISE AAAAAAAA FAAAAAAAAAAAUUUUUUUUUUUUU");
        selectedHotel = null;
    }

    public List<SelectItem> getListeHotel() {
        if (listeHotel == null) {
            if (selectedVille == null || selectedVille.getIdVille() == null) {
                return new ArrayList<SelectItem>();
            }
            System.out.println("Id Ville = " + selectedVille.getNom());
            return buildSelectCollection(getAllHotel(), "nom");
        } else {
            return listeHotel;
        }
    }

    public List<FicheHotel> getAllHotel() {
        if (selectedVille == null) {
            return new ArrayList<FicheHotel>();
        }
        return agenceMetier.getAllHotel(selectedVille.getIdVille());
    }

    public void setListeHotel(List<SelectItem> listeHotel) {
        this.listeHotel = listeHotel;
    }

    public FicheHotel getSelectedHotel() {
        return selectedHotel;
    }

    public void setSelectedHotel(FicheHotel selectedHotel) {
        this.selectedHotel = selectedHotel;
    }

    public ListDataModel getListePeriode()
    {
            if(selectedHotel != null && selectedHotel.getIdFicheHotel() > 0)
                listePeriode = new ListDataModel((List) selectedHotel.getPeriodeTarifCollection());
            else
                listePeriode = null;
        return listePeriode;
    }

    public void setListePeriode(ListDataModel listePeriode)
    {
        this.listePeriode = listePeriode;
    }
    
   
    public PeriodeTarif getCurrentPeriode()
    {
        return currentPeriode;
    }

    public void setCurrentPeriode(PeriodeTarif currentPeriode)
    {
        this.currentPeriode = currentPeriode;
    }
       

    public Client getClient()
    {
        if(client == null)
            client = new Client();
        return client;
    }

    public void setClient(Client client)
    {
        this.client = client;
    }
   
    public Reservation getReservation()
    {
        if(reservation == null)
            reservation = new Reservation();
        return reservation;
    }

    public void setReservation(Reservation reservation)
    {
        this.reservation = reservation;
    }

    public List<SelectItem> getListeTypeChambre()
    {
        if(listeTypeChambre == null){
            return buildSelectCollection(reservationMetier.getAllTypeChambre(), "libelle"); 
        }
           
        else
            return listeTypeChambre;
    }

    public void setListeTypeChambre(List<SelectItem> listeTypeChambre)
    {
        this.listeTypeChambre = listeTypeChambre;
    }

    public TypeChambre getSelectedTypeChambre()
    {
        return selectedTypeChambre;
    }

    public void setSelectedTypeChambre(TypeChambre selectedTypeChambre)
    {
        this.selectedTypeChambre = selectedTypeChambre;
    }
    
        
    public Agence getCurrentAgence()
    {
        if(currentAgence == null)
           currentAgence = reservationMetier.getCurrentAgence();
        return currentAgence;
    }

    public void setCurrentAgence(Agence currentAgence)
    {
        this.currentAgence = currentAgence;
    }

    public float getTotal()
    {
        return total;
    }

    public void setTotal(float total)
    {
        this.total = total;
    }

    public boolean isConfirmTotal()
    {
        return confirmTotal;
    }

    public void setConfirmTotal(boolean confirmTotal)
    {
        this.confirmTotal = confirmTotal;
    }
     public String clicReserv()
    {
        System.out.println("Clic sur btn Reserv");
        setCurrentPeriode((PeriodeTarif)listePeriode.getRowData());
        return "reserve";
    }
     
// ******************* METHODES **************************
     
    /**
     *  Clic sur le bouton de réservation
     */
    public String clicReservation()
    {
        reservationMetier.creerClient(client);
        if(reservationMetier.creerReservation(reservation,client, getCurrentAgence() , selectedHotel, getSelectedTypeChambre()))
            addMessage(FacesMessage.SEVERITY_INFO, "Votre reservation a bien été enregistré");
        return null;
    }
    
    /**
     * Formate la date afin de pouvoir la comparé
     * @param laDate
     */
     private void formatDate(Date laDate)
    {
        laDate.setHours(0);
        laDate.setMinutes(0);
        laDate.setSeconds(0);
        laDate.setSeconds(0);
    }
     
     /**
      * Clique sur le bouton pour avoir le total de la commande
      * @return
      */
    public String clicTotal()
    {   
        formatDate(reservation.getDateEntree());
        formatDate(reservation.getDateSortie());
        formatDate(currentPeriode.getDateDebut());
        formatDate(currentPeriode.getDateFin());
        
        if(reservation.getDateEntree().before(currentPeriode.getDateFin())  && (reservation.getDateEntree().after(currentPeriode.getDateDebut()) || reservation.getDateEntree().equals(currentPeriode.getDateDebut()))
           && (reservation.getDateSortie().before(currentPeriode.getDateFin())  || reservation.getDateSortie().equals(currentPeriode.getDateFin()) && reservation.getDateSortie().after(currentPeriode.getDateDebut()))) 
        {
            Date d =  new Date(reservation.getDateSortie().getTime() - reservation.getDateEntree().getTime());
            int nbJours = (int) (d.getTime() / (1000 * 60 * 60 * 24));
            System.out.println("diff =" + nbJours);
            switch(selectedTypeChambre.getIdTypeChambre())
            {
                case 1 : total = nbJours * currentPeriode.getPrixSimple(); 
                break;
                case 2 : total = nbJours * currentPeriode.getPrixDouble();
                break;
                case 3 : total = nbJours * currentPeriode.getPrixSuite();
                break;
            }
            System.out.println("Total = " +total);
        }
        else
            addMessage(FacesMessage.SEVERITY_ERROR, "Les dates ne correspondent pas à la période seléctionné");
        return null;
    }
    
    /**
     * Clic sur le bouton pour terminer la reservation
     * @return
     */
    public String clicConfirmeTotal()
    {
        setConfirmTotal(true);
        return null;
    }



}
